package com.zyp.messageboard.controller.filter;

import com.zyp.messageboard.util.EncryptionUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;

import java.io.IOException;

@WebFilter("/login")
public class EncryptionFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        // 获取加密后的用户名和密码
        String encryptedUsername = httpRequest.getParameter("encryptedUsername");
        String encryptedPassword = httpRequest.getParameter("encryptedPassword");

        // 打印接收到的加密数据
        System.out.println("Received Encrypted Username: " + encryptedUsername);
        System.out.println("Received Encrypted Password: " + encryptedPassword);

        if (encryptedUsername != null && encryptedPassword != null) {
            // 解密用户名和密码
            String username = EncryptionUtil.decryptData(encryptedUsername);
            String password = EncryptionUtil.decryptData(encryptedPassword);

            // 打印解密后的数据
            System.out.println("Decrypted Username: " + username);
            System.out.println("Decrypted Password: " + password);

            // 创建包装的请求对象，以便在后续的处理中使用解密后的数据
            HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapper(httpRequest) {
                @Override
                public String getParameter(String name) {
                    if ("username".equals(name)) {
                        return username;
                    } else if ("password".equals(name)) {
                        return password;
                    }
                    return super.getParameter(name);
                }
            };

            chain.doFilter(wrappedRequest, response);
        } else {
            // 打印未接收到加密数据的情况
            System.out.println("No encrypted data received.");
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Initialization code, if needed
    }

    @Override
    public void destroy() {
        // Cleanup code, if needed
    }
}
